package com.dtguai.web.web.fastDfs.controller.fdfs;


import com.dtguai.web.base.action.BaseAction;
import com.dtguai.web.common.annotation.SysLog;
import com.dtguai.web.common.error.ErrorCode;
import com.dtguai.web.common.exception.DefinedException;
import com.dtguai.web.common.validator.BaseAssert;
import com.dtguai.web.common.validator.ValidatorUtils;
import com.dtguai.web.protocol.response.ApiResponse;
import com.dtguai.web.util.Servlets;
import com.dtguai.web.web.fastDfs.form.sysDefFdfs.AddSysDefFdfsForm;
import com.dtguai.web.web.fastDfs.form.sysDefFdfs.SysDefFdfsForm;
import com.dtguai.web.web.fastDfs.model.SysDefFdfs;
import com.dtguai.web.web.fastDfs.service.SysDefFdfsService;
import com.github.pagehelper.PageInfo;
import com.google.common.net.HttpHeaders;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponses;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Optional;

/**
 * @author guoLiang
 * @date 2018-12-11 02:43:02
 */
@Slf4j
@RestController
@RequestMapping("/web/fdfs/controller/fdfs")
@Api(value = "web-fdfs-文件上传接口", tags = {"web-fdfs-文件上传接口"})
public class SysDefFdfsApi extends BaseAction {

    @Autowired
    private SysDefFdfsService sysDefFdfsService;

    /**
     * 分页查询 注意返回信息是 PageInfo 自带分页所有信息
     *
     * @param sysDefFdfs 入参对象Form
     * @author guo
     * @date 2019-06-28 17:32:43
     */
    @ApiOperation(value = "分页查询-返回PageInfo", notes = "分页查询-返回PageInfo")
    @GetMapping(value = "/list", produces = "application/json;charset=UTF-8")
    @RequiresPermissions("sys:fdfs:all")
    public ResponseEntity<ApiResponse<PageInfo<SysDefFdfs>>> list(SysDefFdfsForm sysDefFdfs) {
        // 表单校验
        ValidatorUtils.validateEntity(sysDefFdfs);
        List<SysDefFdfs> sysDefFdfsList = sysDefFdfsService.selectByPage(sysDefFdfs, true, SysDefFdfs.class);
        return ResponseEntity.ok(new ApiResponse<PageInfo<SysDefFdfs>>(new PageInfo<SysDefFdfs>(sysDefFdfsList)));
    }

    /**
     * 上传文件
     */
    @ApiOperation(value = "上传文件", notes = "上传文件")
    @PostMapping("/upload")
    @RequiresPermissions("sys:fdfs:all")
    @SysLog("上传文件")
    public ResponseEntity<ApiResponse<SysDefFdfs>> upload(AddSysDefFdfsForm fdfs) {
        ValidatorUtils.validateEntity(fdfs);
        return ResponseEntity.ok(new ApiResponse<SysDefFdfs>(sysDefFdfsService.upload(fdfs.getFile())));
    }

    /**
     * 下载文件
     *
     * @param id id
     * @author tangyi
     * @date 2018/10/30 22:26
     */
    @ApiOperation(value = "下载附件", notes = "根据ID下载附件")
    @GetMapping(value = "/download", produces = "application/json;charset=UTF-8")
    @ApiImplicitParam(name = "id", value = "附件ID", required = true, example = "1")
    @RequiresPermissions("sys:fdfs:all")
    @ApiResponses({
            @io.swagger.annotations.ApiResponse(code = 1022, message = "id不能为空")
    })
    public void download(Integer id, HttpServletRequest request, HttpServletResponse response) {
        BaseAssert.isNull(id, ErrorCode.ID_NOT_NULL);
        SysDefFdfs fdfs = sysDefFdfsService.selectByKey(id);
        if (fdfs == null) {
            throw new DefinedException("附件不存在！");
        }
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = sysDefFdfsService.download(fdfs);
            // 输出流
            outputStream = response.getOutputStream();
            response.setContentType("application/zip");
            response.setHeader(HttpHeaders.CACHE_CONTROL, "max-age=10");
            // IE之外的浏览器使用编码输出名称
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, Servlets.getDownName(request, fdfs.getName()));
            response.setContentLength(inputStream.available());
            // 下载文件
            FileCopyUtils.copy(inputStream, outputStream);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
        }
    }

    /**
     * 删除附件
     *
     * @param ids id_list
     * @return ResponseBean
     * @author tangyi
     * @date 2018/10/30 22:44
     */
    @ApiOperation(value = "删除附件", notes = "根据ID删除附件")
    @SysLog("删除附件")
    @DeleteMapping(value = "/delete", produces = "application/json;charset=UTF-8")
    @RequiresPermissions("sys:fdfs:all")
    @ApiResponses({
            @io.swagger.annotations.ApiResponse(code = 1022, message = "id不能为空")
    })
    @ApiImplicitParam(name = "id", value = "主键id", required = true)
    public ResponseEntity<ApiResponse> delete(@RequestBody List<Integer> ids) {

        BaseAssert.isNull(ids, ErrorCode.ID_NOT_NULL);

        ids.parallelStream().forEach(y ->
                Optional.ofNullable(sysDefFdfsService.selectByKey(y))
                        .ifPresent(z -> sysDefFdfsService.delete(z))
        );

        return ResponseEntity.ok(new ApiResponse());
    }

}